<template>
    <van-sku v-model="skuVisible"
             :sku="sku"
             :initial-sku="initialSku"
             :goods="goods"
             :goods-id="product.id"
             close-on-click-overlay
             @sku-selected="handleSkuSelected"
             @add-cart="handleAddToCart"
             @buy-clicked="handleBuyClick"
             @ok="handleOkClick"
             ref="sku">
        <template #sku-actions="props">
            <div class="van-sku-actions">
                <van-button v-if="addToCartVisible" square size="large" type="warning"
                            :loading="addToCartLoading"
                            @click="props.skuEventBus.$emit('sku:addCart')">
                    {{addToCartText}}
                </van-button>
                <van-button v-if="okVisible" square size="large" type="danger"
                            :loading="okLoading"
                            @click="$refs.sku.onBuyOrAddCart('ok')">
                    {{okText}}
                </van-button>
                <van-button v-if="buyVisible" square size="large" type="danger"
                            :loading="buyLoading"
                            @click="props.skuEventBus.$emit('sku:buy')">
                    {{buyText}}
                </van-button>
            </div>
        </template>
        <template #sku-stepper v-if="!stepperVisible">
            <div></div>
        </template>
    </van-sku>
</template>

<script>
  import { Button, Sku } from "vant"
  import * as _ from "lodash"
  import { catalog, checkout } from "@mall/api-services"

  function variantToSku(variant) {
    return {
      id: variant.id,
      price: variant.price * 100,
      ...(_.transform(variant.optionSelections, (result, selection) => {
        result[`option_${selection.nameId}`] = selection.valueId
      }, {})),
      variant,
      stock_num: variant.inventoryQuantity,
    }
  }

  export default {
    name: "ProductSelection",
    components: {
      [Button.name]: Button,
      [Sku.name]: Sku,
    },
    model: {
      prop: "visible",
      event: "change",
    },
    props: {
      visible: Boolean,
      product: {
        type: catalog.Product,
        required: true,
      },
      initialVariant: {
        type: catalog.ProductVariant,
      },
      addToCartLoading: Boolean,
      addToCartVisible: {
        type: Boolean,
        default: false,
      },
      addToCartText: {
        type: String,
        default: "加入购物车",
      },
      buyLoading: Boolean,
      buyVisible: {
        type: Boolean,
        default: false,
      },
      buyText: {
        type: String,
        default: "立即购买",
      },
      okLoading: Boolean,
      okVisible: {
        type: Boolean,
        default: false,
      },
      okText: {
        type: String,
        default: "确定",
      },
      stepperVisible: {
        type: Boolean,
        default: true,
      },
    },
    watch: {
      visible: function(visible, oldVisible) {
        if (visible !== oldVisible) {
          this.skuVisible = visible
        }
      },
      skuVisible: function(visible, oldVisible) {
        if (visible !== oldVisible) {
          this.$emit("change", visible)
        }
      },
    },
    computed: {
      skuTree() {
        const { options, variants } = this.product

        function resolveImage(nameId, valueId) {
          const variant = _.find(variants, variant => !_.isUndefined(
            _.find(variant.optionSelections,
              selection => selection.nameId === nameId && selection.valueId === valueId)))
          return _.isUndefined(variant) ? undefined : _.first(variant.imageUrls)
        }

        return _.map(options, (option, index) => ({
          k: option.name,
          k_id: option.id,
          k_s: `option_${option.id}`,
          v: _.map(option.values, value => ({
            id: value.id,
            name: value.label,
            imgUrl: index === 0 ? resolveImage(option.id, value.id) : undefined,
          })),
        }))
      },
      skuList() {
        const { variants } = this.product
        return _.map(variants, variantToSku)
      },
      sku: function() {
        const { product } = this
        const { skuTree: tree, skuList: list } = this
        return {
          tree,
          list,
          price: product.price, // 默认价格（单位元）
          stock_num: product.inventoryQuantity,
          none_sku: false, // 是否无规格商品
          hide_stock: false, // 是否隐藏剩余库存
        }
      },
      initialSku() {
        const { initialVariant } = this
        const initialSku = _.isEmpty(initialVariant) ? _.first(this.skuList) : variantToSku(initialVariant)
        return _.isUndefined(initialSku) ? {} : {
          ...initialSku,
          selectedNum: 1,
        }
      },
      goods() {
        const { product } = this
        const { name: title, imageUrls, price } = product
        return {
          title,
          picture: _.first(imageUrls),
          price,
        }
      },
    },
    data() {
      return {
        skuVisible: false,
      }
    },
    methods: {
      emitCheckout(type, sku) {
        const item = new checkout.CheckoutItem()
        item.productId = sku.goodsId
        item.variantId = sku.selectedSkuComb.id
        item.quantity = sku.selectedNum
        this.$emit(type, item)
      },
      handleAddToCart(sku) {
        this.emitCheckout("add-to-cart", sku)
      },
      handleBuyClick(sku) {
        this.emitCheckout("buy", sku)
      },
      handleOkClick(sku) {
        this.emitCheckout("ok", sku)
      },
      handleSkuSelected({ selectedSkuComb }) {
        if (selectedSkuComb) {
          this.$emit("change-variant", selectedSkuComb.variant)
        }
      },
    },

  }
</script>

<style scoped>

</style>
